<?php

namespace App\Http\Controllers\Api;

use App\Models\BookComment;
use App\Models\BookList;
use App\Models\BookListBookRelation;
use App\Models\BookListCategory;
use App\Models\User;
use Illuminate\Http\Request;
use DB;
use App\Common\ErrorCode;

class BookListsController extends BaseController
{
    public function categories()
    {
        $categories = BookListCategory::query()->select('id','title')->where('deleted',0)->get();
        return $this->res([
            'data' => $categories
        ]);
    }

    public function index(Request $request)
    {
        $category_id = intval($request->input('category_id'));
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));

        $builder = BookList::query()->with(['user_collects','books'])->where('deleted',0)->where('status',1);
        if(!empty($category_id))
        {
            $builder->where('category_id',$category_id);
        }

        //echo $per_page;die;
        $list = $builder->orderBy('order','asc')->paginate($per_page,['id','title','list_image','total_collect_num'],'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $user_collects = [];
                if(!empty($item->user_collects))
                {
                    foreach ($item->user_collects as $key=>$value)
                    {
                        if($key == 3)
                        {
                            break;
                        }
                        $user_collects[] = [
                            'user_id' => $value['id'],
                            'user_wechat_avatar' => $value['wechat_avatar']
                        ];
                    }
                }
                unset($item['user_collects']);
                //var_dump($user_collects);die;
                $items[] = [
                    'id' => $item->id,
                    'title' => $item->title,
                    'list_image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['list_image'],
                    'total_collect_num' => $item->total_collect_num,
                    'user_collects' => $user_collects,
                    'book_num' => count($item->books),
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count' => $list->total(),
                'page_count' => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page' => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(BookList $bookList, Request $request)
    {
        $user_id = intval($request->input('user_id'));

        $info = BookList::query()->with(['books','books.comments','user_collects'])->where('id',$bookList->id)->first();
        //dd($info->user_collects);
        $is_collect = 0;
        if(!empty($user_id))
        {
            $colelct = DB::table('book_list_user_collect_relations')->where('book_list_id',$bookList->id)->where('user_id',$user_id)->first();
            if(!empty($colelct))
            {
                $is_collect = 1;
            }
        }

        $user_collects = [];
        if(!empty($info->user_collects))
        {
            foreach ($info->user_collects as $k=>$v)
            {
                if($k == 3)
                {
                    break;
                }
                $user_collects[] = [
                    'user_id' => $v['id'],
                    'user_wechat_avatar' => $v['wechat_avatar']
                ];
            }
        }

        $book_list_info = [
            'detail_image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$info['detail_image'],
            'title' => $info['title'],
            'total_collect_num' => $info['total_collect_num'],
            'user_collects' => $user_collects,
            'book_num' => count($info->books),
            'is_collect' => $is_collect,
            'intro' => $info->intro
        ];

        $books = [];
        if(!empty($info->books))
        {
            foreach ($info->books as $v)
            {
                $first_comment = BookComment::query()->with(['user'])->where('deleted',0)->where('book_id',$v['id'])->orderBy('good_num','desc')->first();

                $books[] = [
                    'id' => $v['id'],
                    'total_read_num' => $v['total_read_num'],
                    'title' => $v['title'],
                    'author' => $v['author'],
                    'store' => $v['store'],
                    'douban_score' => $v['douban_score'],
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['image'],
                    'intro' => str_replace("\r\n",'',strip_tags($v['intro'])),
                    'comments_num' => count($v->comments),
                    'first_comment_content' => !empty($first_comment->content)?$first_comment->content:'',
                    'first_comment_user_wechat_avatar' => !empty($first_comment->user->wechat_avatar)?$first_comment->user->wechat_avatar:'',
                    'first_comment_user_wechat_nickname' => !empty($first_comment->user->wechat_nickname)?$first_comment->user->wechat_nickname:'',
                ];
            }
        }
        return $this->res([
            'data' => [
                'book_list_info' => $book_list_info,
                'books' => $books
            ]
        ]);
    }

    public function collect(Request $request)
    {
        $type = intval($request->input('type')); //1收藏 2取消收藏
        $user_id = intval($request->input('user_id'));
        $book_list_id = intval($request->input('book_list_id'));

        if(!in_array($type,[1,2]))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        if(!User::query()->where('id',$user_id)->exists())
        {
            return $this->error(10000,'用户不存在');
        }

        if(!BookList::query()->where('id',$book_list_id)->exists())
        {
            return $this->error(10000,'书单不存在');
        }

        $record = DB::table('book_list_user_collect_relations')->where(['user_id'=>$user_id,'book_list_id'=>$book_list_id])->first();
        if($type == 1)
        {
            if(!empty($record))
            {
                return $this->error(10000,'书单已收藏');
            }
            //收藏
            DB::table('book_list_user_collect_relations')->insert([
                'user_id' => $user_id,
                'book_list_id' => $book_list_id,
                'user_type' => 1
            ]);
            BookList::query()->where('id',$book_list_id)->increment('user_collect_num');
            BookList::query()->where('id',$book_list_id)->increment('total_collect_num');
        }
        else
        {
            if(empty($record))
            {
                return $this->error(10000,'书单尚未收藏');
            }
            //取消收藏
            DB::table('book_list_user_collect_relations')->where('id',$record->id)->delete();
            BookList::query()->where('id',$book_list_id)->decrement('user_collect_num');
            BookList::query()->where('id',$book_list_id)->decrement('total_collect_num');
        }

        return $this->success();
    }
}
